package com.example.myserver;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;

public class MainActivity extends AppCompatActivity {

    TextView tv_main_content;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread(new MyServer()).start();
    }
}

class MyServer implements Runnable{
    //定义保存所有Socket的ArrayList
    public static ArrayList<Socket> socketList=null;
    public MyServer(){
        socketList=new ArrayList<>();
    }

    @Override
    public void run() {
        try {
            //此行代码会阻塞，将一直等待别人的连接
            ServerSocket ss=new ServerSocket(40000);
            while(true){
                Socket sk=ss.accept();
                socketList.add(sk);
                //每当客户端连接后启动一条ServerThread线程为该客户端服务
                new Thread(new ServerThread(sk)).start();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
//负责处理每个线程通信的线程类
class ServerThread implements Runnable {
    //定义当前线程所处理的Socket
    Socket s = null;
    // 该线程所处理的Socket所对应的输入流
    BufferedReader br = null;
    //初始化 将参数socket赋给成员s
    //IOException输入或输出异常
    public ServerThread(Socket s) throws IOException {
        this.s = s;
        // 初始化该Socket对应的输入流
        //将客户端socket输入流的内容赋给br
        br = new BufferedReader(new InputStreamReader(s.getInputStream(), "utf-8"));
    }

    @Override
    public void run() {
        String content = null;
        // 采用循环不断从Socket中读取客户端发送过来的数据
        while ((content = readFromClient()) != null) {
            // 遍历socketList中的每个Socket，
            // 将读到的内容向每个Socket发送一次

            for (Iterator<Socket> it = MyServer.socketList.iterator(); it.hasNext(); ) {
                Socket outSk = it.next();
                try {
                    OutputStream os = outSk.getOutputStream();
                    os.write((content + "\n").getBytes());
                    //IOException输入或输出异常
                } catch (IOException e) {
                    e.printStackTrace();
                    it.remove();
                }
            }
        }


    }
    // 定义读取客户端数据的方法
    private String readFromClient() {
        try {
            return br.readLine();

        }   // 如果捕捉到异常，表明该Socket对应的客户端已经关闭
        catch (IOException e) {
            e.printStackTrace();
            MyServer.socketList.remove(s);
        }
        return null;
    }
}
